﻿using System;
using System.Runtime.InteropServices;

namespace MediaRemoteServer
{
    class VolumeControl
    {

        [DllImport("winmm.dll")]
        private static extern int waveOutGetVolume(IntPtr hwo, out uint dwVolume);

        [DllImport("winmm.dll")]
        private static extern int waveOutSetVolume(IntPtr hwo, uint dwVolume);

        public static float getVolumePercent()
        {
            float currentVolume = (float)Math.Round(getVolume() * 100, 0);
            Console.WriteLine("current volume: {0}%", currentVolume);
            return currentVolume;
        }

        public static float getVolume()
        {
            uint curVol = 0;
            waveOutGetVolume(IntPtr.Zero, out curVol);
            ushort calcVol = (ushort)(curVol & 0xffff);
            float currentVolume = (float)calcVol / ushort.MaxValue;
            Console.WriteLine("current volume: {0}", currentVolume);
            return currentVolume;
        }

        public static void setVolumePercent(float volume)
        {
            setVolume((float)Math.Round(volume, 0) / 100);
        }

        public static void setVolume(float volume)
        {
            volume = ushort.MaxValue * volume;
            uint volumeBothChannels = (((uint)volume & 0xffff) | ((uint)volume << 16));
            Console.WriteLine("set volume: {0}", volumeBothChannels);
            waveOutSetVolume(IntPtr.Zero, volumeBothChannels);
        }

    }
}
